package com.brower.project.net

import android.util.Log
import androidx.viewbinding.BuildConfig
import com.brower.project.net.api.HeadersInterceptor
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 * desc   : 基础业务的的RetrofitClient
 * date   : 2020/09/01
 * version: 1.0
 */
class RetrofitClient {
    companion object {
        // 基础host
        private const val BASE_URL = "https://www.wanandroid.com/"
        private const val DEFAULT_TIMEOUT = 20L
    }

    private val okHttpClient: OkHttpClient
        get() {
            return OkHttpClient.Builder().apply {
                // 设置超时时间
                connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                retryOnConnectionFailure(true) // 连接失败时重试
//                // https证书免验证, 信任所有https请求
//                hostnameVerifier(HttpSslFactory.generateUnSafeHostnameVerifier())
//                if (sslSocketFactory != null && trustManager != null) {
//                    sslSocketFactory(sslSocketFactory, trustManager)
//                }
                // 日志拦截器
                addInterceptor(HttpLoggingInterceptor {
                    Log.i("====", ": $it")
                }.apply {
                    setLevel(HttpLoggingInterceptor.Level.BODY)
                })
                addInterceptor(SaveCookiesInterceptor())
                addInterceptor(ReadCookiesInterceptor())
            }.build()
        }

    fun <S> getService(serviceClass: Class<S>): S {
        val gson = GsonBuilder().create()

        return Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .baseUrl(BASE_URL)
            .build().create(serviceClass)
    }
}
